package com.gw.booking.service;

import com.alibaba.fastjson.JSONObject;
import com.gw.booking.common.Constant;
import com.gw.booking.common.WXAppletUserInfo;
import com.gw.booking.entity.AccessToken;
import config.Config;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Date;

@Service
public class AccessTokenService {

    @Autowired
    protected SessionFactory sessionFactory;

    public String txGetAccessToken(String type) {
        Session session = sessionFactory.getCurrentSession();
        String hql = " from AccessToken where type = :type ";
        AccessToken accessToken = (AccessToken) session.createQuery(hql)
                .setParameter("type", type)
                .setMaxResults(1).uniqueResult();
        if (accessToken == null) {
            return txBuild(type);
        } else if (accessToken.getTimeLimit() < (new Date().getTime())) {
            return txRefresh(type, accessToken);
        }
        return accessToken.getToken();
    }

    public String txBuild(String type) {
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        Session session = sessionFactory.getCurrentSession();
        JSONObject jsonObject;
        if (Constant.USER_TYPE_MERCHANT.equals(type)) {
            jsonObject = WXAppletUserInfo.getAccessTokenForMerchant();
        } else {
            jsonObject = WXAppletUserInfo.getAccessTokenForDiner();
        }
        String access_token = (String) jsonObject.get("access_token");
        AccessToken accessToken = new AccessToken();
        accessToken.setType(type);
        accessToken.setCreatedAt(ts);
        accessToken.setToken(access_token);
        accessToken.setTimeLimit(System.currentTimeMillis() + Config.accessTokenLimit);
        session.save(accessToken);
        session.flush();
        return access_token;
    }

    public String txRefresh(String type, AccessToken accessToken) {
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        Session session = sessionFactory.getCurrentSession();
        JSONObject jsonObject;
        if (Constant.USER_TYPE_MERCHANT.equals(type)) {
            jsonObject = WXAppletUserInfo.getAccessTokenForMerchant();
        } else {
            jsonObject = WXAppletUserInfo.getAccessTokenForDiner();
        }
        String access_token = (String) jsonObject.get("access_token");
        accessToken.setToken(access_token);
        accessToken.setTimeLimit(System.currentTimeMillis() + Config.accessTokenLimit);
        accessToken.setUpdatedAt(ts);
        session.save(accessToken);
        session.flush();
        return access_token;
    }
}
